package com.dayou.controller;
import java.util.Base64;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.dayou.common.utils.IpUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "request")
public class RequestController {
	@RequestMapping("/get")
	@ResponseBody
	public JSONObject get(String url, String params,String sessionId,HttpServletRequest req){
		JSONObject jsonParam = JSON.parseObject(params);
		@SuppressWarnings("unchecked")
		Map<String,Object> paramMap = JSONObject.toJavaObject(jsonParam,Map.class);
		int paramCount = 0;
		String paramSufixx = "";
		if(paramMap != null){
			Set<String> keys = paramMap.keySet();
			Iterator<String> kIt = keys.iterator();
			while(kIt.hasNext()){
				String key = kIt.next();
				String value = paramMap.get(key).toString();
				String sperator;
				if(paramCount < 1){
					sperator = "?";
				}else{
					sperator = "&";
				}
				++paramCount;
				paramSufixx+=(sperator+key+"="+value);
			}
		}
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("session_id", sessionId);
		HttpEntity<JSONObject> request = new HttpEntity<>(headers);
		RestTemplate restTemplate = new RestTemplate();
		String ip = IpUtils.getIpAddr(req);
		System.out.println("请求ip:"+ip+"\n请求路径:"+url+paramSufixx+"\n请求参数:"+jsonParam);
		RequestCallback requestCallback = restTemplate.httpEntityCallback(request,Map.class);
		ResponseExtractor<ResponseEntity<JSONObject>> responseExtractor = restTemplate.responseEntityExtractor(JSONObject.class);
		ResponseEntity<JSONObject> result = restTemplate.execute(url+paramSufixx,HttpMethod.GET,requestCallback,responseExtractor);
		return result.getBody();
	}
	@RequestMapping("/post")
	@ResponseBody
	public JSONObject post(String url, String params,String sessionId,HttpServletRequest req){
		JSONObject jsonParam = JSON.parseObject(params);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("session_id", sessionId);
		HttpEntity<JSONObject> request = new HttpEntity<>(jsonParam,headers);
		String ip = IpUtils.getIpAddr(req);
		System.out.println("请求ip:"+ip+"\n请求路径:"+url+"\n请求参数:"+request.getBody());
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);
		return response.getBody();
	}

	/**
	 * 1比n比对
	 */
	@RequestMapping("/oneToMany")
	@ResponseBody
	public JSONObject oneToMany(String params,HttpServletRequest req){
		String url = "http://38.145.205.150:11180/business/api/retrieval_repository";
		JSONObject jsonParam = JSON.parseObject(params);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		JSONObject loginRes = this.post("http://38.145.205.150:11180/business/api/login","{\"name\":\"regist\",\"password\":\"5ca41519f429ad434c771a6b86e99f25\"}",null,req);
		String sessionId = loginRes.getString("session_id");
		headers.set("session_id", sessionId);
		HttpEntity<JSONObject> request = new HttpEntity<>(jsonParam,headers);
		String ip = IpUtils.getIpAddr(req);
		System.out.println("请求ip:"+ip+"\n请求路径:"+url+"\n请求参数:"+request.getBody());
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);
		return response.getBody();
	}
	/**
	 * 上传图片
	 */
	@RequestMapping("/uploadImage")
	@ResponseBody
	public JSONObject uploadImage(String params,HttpServletRequest req){
		String url = "http://38.145.205.150:11180/business/api/repository/picture/batch_single_person";
		JSONObject jsonParam = JSON.parseObject(params);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		JSONObject loginRes = this.post("http://38.145.205.150:11180/business/api/login","{\"name\":\"regist\",\"password\":\"5ca41519f429ad434c771a6b86e99f25\"}",null,req);
		String sessionId = loginRes.getString("session_id");
		headers.set("session_id", sessionId);
		HttpEntity<JSONObject> request = new HttpEntity<>(jsonParam,headers);
		String ip = IpUtils.getIpAddr(req);
		System.out.println("请求ip:"+ip+"\n请求路径:"+url+"\n请求参数:"+request.getBody());
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);
		return response.getBody();
	}
	/**
	 * 人脸检测
	 */
	@RequestMapping("/faceDetection")
	@ResponseBody
	public JSONObject faceDetection(String params,HttpServletRequest req){
		String url = "http://38.145.205.150:11180/business/api/face_detection";
		JSONObject jsonParam = JSON.parseObject(params);
		HttpHeaders headers = new HttpHeaders();
		System.out.println(jsonParam);
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		JSONObject loginRes = this.post("http://38.145.205.150:11180/business/api/login","{\"name\":\"regist\",\"password\":\"5ca41519f429ad434c771a6b86e99f25\"}",null,req);
		String sessionId = loginRes.getString("session_id");
		headers.set("session_id", sessionId);
		HttpEntity<JSONObject> request = new HttpEntity<>(jsonParam,headers);
		String ip = IpUtils.getIpAddr(req);
		System.out.println("请求ip:"+ip+"\n请求路径:"+url+"\n请求参数:"+request.getBody());
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);
		return response.getBody();
	}
	/**
	 * 人脸库检索接口
	 */
	@RequestMapping("/getImgUri")
	@ResponseBody
	public String getImgUri(String params,HttpServletRequest req){
		String url = "http://38.145.205.150:11180/business/api/condition/query_repository";
		JSONObject jsonParam = JSON.parseObject(params);
		HttpHeaders headers = new HttpHeaders();
		System.out.println(jsonParam);
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		JSONObject loginRes = this.post("http://38.145.205.150:11180/business/api/login","{\"name\":\"regist\",\"password\":\"5ca41519f429ad434c771a6b86e99f25\"}",null,req);
		String sessionId = loginRes.getString("session_id");
		headers.set("session_id", sessionId);
		HttpEntity<JSONObject> request = new HttpEntity<>(jsonParam,headers);
		String ip = IpUtils.getIpAddr(req);
		System.out.println("请求ip:"+ip+"\n请求路径:"+url+"\n请求参数:"+request.getBody());
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);
		JSONObject resObj = response.getBody();
		JSONArray resArray = resObj.getJSONArray("results");
		String imgUri = resArray.getJSONObject(0).getString("face_image_uri");
		return imgUri;
	}


	/**
	 * 取图接口
	 */
	@RequestMapping(value="/getImage",produces="image/png")
	@ResponseBody
	public Object getImage(String imgUri,HttpServletRequest req){
		// 登录依图平台并拿到session_id
		JSONObject loginRes = this.post("http://38.145.205.150:11180/business/api/login","{\"name\":\"regist\",\"password\":\"5ca41519f429ad434c771a6b86e99f25\"}",null,req);
		String sessionId = loginRes.getString("session_id");
		String base64Str = Base64.getEncoder().encodeToString(imgUri.getBytes());
		//String base64Str = Base64.getEncoder().encodeToString("normal://surveillance-image/20190723/hjCviSyYF1AZv66mgIks5Q==@1".getBytes());
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("session_id", sessionId);
		HttpEntity<String> request = new HttpEntity<>(headers);
		RestTemplate restTemplate = new RestTemplate();
		RequestCallback requestCallback = restTemplate.httpEntityCallback(request,Map.class);
		ResponseExtractor<ResponseEntity<byte[]>> responseExtractor = restTemplate.responseEntityExtractor(byte[].class);
		ResponseEntity<byte[]> result = restTemplate.execute("http://38.145.205.150:11180/business/api/storage/image?uri_base64="+base64Str, HttpMethod.GET,requestCallback,responseExtractor);
		return result.getBody();
	}
	/**
	 * 删图接口
	 */
	@RequestMapping(value="/delImage")
	@ResponseBody
	public boolean delImage(String params,HttpServletRequest req){
		String url = "http://38.145.205.150:11180/business/api/face/delete";
		JSONObject jsonParam = JSON.parseObject(params);
		HttpHeaders headers = new HttpHeaders();
		System.out.println(jsonParam);
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		JSONObject loginRes = this.post("http://38.145.205.150:11180/business/api/login","{\"name\":\"regist\",\"password\":\"5ca41519f429ad434c771a6b86e99f25\"}",null,req);
		String sessionId = loginRes.getString("session_id");
		headers.set("session_id", sessionId);
		HttpEntity<JSONObject> request = new HttpEntity<>(jsonParam,headers);
		String ip = IpUtils.getIpAddr(req);
		System.out.println("请求ip:"+ip+"\n请求路径:"+url+"\n请求参数:"+request.getBody());
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);
		JSONObject resObj = response.getBody();
		int rtn = resObj.getInteger("rtn");
		return rtn == 0;
	}
}
